package com.huicoo.forestmanager.ui.patrol.fireAlarm;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.huicoo.forestmanager.CustomUtils;
import com.huicoo.forestmanager.R;
import com.huicoo.forestmanager.base.BaseActivity;
import com.huicoo.forestmanager.network.HttpService;
import com.huicoo.forestmanager.network.bean.patrol.AttachmentEntity;
import com.huicoo.forestmanager.network.bean.patrol.EventTypeBean;
import com.huicoo.forestmanager.network.bean.patrol.ReportEventBean;
import com.huicoo.forestmanager.network.bean.patrol.UploadFileBean;
import com.huicoo.forestmanager.others.MediaEvent;
import com.huicoo.forestmanager.others.WebRefreshEvent;
import com.huicoo.forestmanager.ui.media.BrowseImageActivity;
import com.huicoo.forestmanager.ui.patrol.fireAlarm.contract.AlarmContract;
import com.huicoo.forestmanager.ui.patrol.fireAlarm.presenter.AlarmPresenter;
import com.huicoo.forestmanager.ui.patrol.forestCampTask.contract.ForestCampTaskVerifyEventContract;
import com.huicoo.forestmanager.util.AttachmentHelper;
import com.huicoo.forestmanager.util.DisplayUtil;
import com.huicoo.forestmanager.util.JsonUtils;
import com.huicoo.forestmanager.util.LogUtils;
import com.huicoo.forestmanager.util.StringUtil;
import com.huicoo.forestmanager.util.WeakHandler;
import com.huicoo.forestmanager.util.audio.AudioRecordDialog;
import com.huicoo.forestmanager.util.audio.PlayAudioRecordDialog;
import com.huicoo.forestmanager.util.glide.ExploreImageLoader;
import com.huicoo.forestmanager.util.toast.ToastUtils;
import com.huicoo.forestmanager.widget.CameraSelectionDialog;
import com.huicoo.forestmanager.widget.LoadingDialog;
import com.huicoo.forestmanager.widget.tipsview.TipsGroupView;
import com.huicoo.forestmanager.widget.tipsview.TipsItem;
import com.liaoinstan.springview.utils.DensityUtil;
import com.tianditu.android.maps.GeoPoint;
import com.tianditu.android.maps.MapController;
import com.tianditu.android.maps.MapView;
import com.tianditu.android.maps.MyLocationOverlay;
import com.tianditu.android.maps.TErrorCode;
import com.tianditu.android.maps.TGeoAddress;
import com.tianditu.android.maps.TGeoDecode;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.tianditu.android.maps.MapView.LOGO_RIGHT_BOTTOM;
import static com.tianditu.android.maps.MapView.TMapType.MAP_TYPE_IMG;
import static com.tianditu.android.maps.MapView.TMapType.MAP_TYPE_VEC;

/**
 * 火情报警
 */
public class FireAlarmActivity extends BaseActivity implements AlarmContract.View, TGeoDecode.OnGeoResultListener {

    @BindView(R.id.map_view)
    MapView map_view;

    @BindView(R.id.positioning)
    ImageView positioning;

    @BindView(R.id.subtract)
    ImageView subtract;

    @BindView(R.id.add)
    ImageView add;

    @BindView(R.id.map_type_iv)
    ImageView map_type_iv;

    @BindView(R.id.map_type_tv)
    TextView map_type_tv;

    @BindView(R.id.map_type_ll)
    LinearLayout map_type_ll;

    @BindView(R.id.btn_camera)
    ImageView btn_camera;

    @BindView(R.id.btn_record)
    ImageView btn_record;

    @BindView(R.id.ll_attachment)
    LinearLayout ll_attachment;

    @BindView(R.id.et_remark)
    EditText et_remark;

    @BindView(R.id.tab_Layout)
    TabLayout tabLayout;

    @BindView(R.id.tips_view)
    TipsGroupView tips_view;

    private boolean isFireAlarm; //是否火情报警
    private MapController mMapController;
    private MyLocationOverlay myLocationOverlay;
    private TGeoDecode mGeoDecode;

    private List<EventTypeBean.EventTypeData> eventTypeList;
    private List<TipsItem> tipsList;

    private LoadingDialog loadingDialog;

    private int voiceCount;  //音频附件累加器

    private String ImagePath = "";
    private String VoicePath = "";
    private String VideoPath = "";
    private String ThumbnailPath = "";

    private WeakHandler handler;

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, FireAlarmActivity.class);
        activity.startActivity(intent);
    }

    public static void start(Activity activity, int isFireAlarm) {
        Intent intent = new Intent(activity, FireAlarmActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("isFireAlarm", isFireAlarm);
        intent.putExtras(bundle);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void captureMediaSuccessEvent(MediaEvent event) {
        LogUtils.v("gogogo on success event = " + event.type + " -- " + event.filePath);
        String filePath = event.filePath;
        int type = event.type;
        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        params.put("IsCheckRepeat", "1");
        params.put("UID", CustomUtils.getUUID());
        AttachmentEntity attachmentEntity = new AttachmentEntity(event.type, AttachmentHelper.getFileName(filePath), new File(filePath), event.during);
        if (loadingDialog != null) {
            loadingDialog.show();
        }
        ((AlarmPresenter) presenter).uploadFile(params, attachmentEntity);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_fire_alarm;
    }

    @Override
    protected void initView() {
        Bundle initBundle = getIntent().getExtras();
        if (initBundle != null) {
            isFireAlarm = initBundle.getInt("isFireAlarm", 0) == 1;
        }

        loadingDialog = new LoadingDialog(this);

        //初始化地图设置
        initMapView();

        //初始化上报面板
        initPanel();

        presenter = new AlarmPresenter(this);

        handler = new WeakHandler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == 333) {
                    LogUtils.v("gogogo handler message = " + (String) (msg.obj));
                    playVideo((String) msg.obj);
                }
                return false;
            }
        });

        //请求问题上报类型
        loadingDialog.show();
        requestData();
    }

    //初始化地图设置
    private void initMapView() {
        //设置启用内置的缩放控件
        map_view.setBuiltInZoomControls(false);

        //得到mMapView的控制权,可以用它控制和驱动平移和缩放
        mMapController = map_view.getController();

        //创建MyLocationOverlay
        myLocationOverlay = new MyLocationOverlay(this, map_view);

        //启用指南针位置更新
        myLocationOverlay.enableCompass();

        //启用我的位置
        myLocationOverlay.enableMyLocation();

        map_view.addOverlay(myLocationOverlay);

        //定位到当前位置
        locateCurrentLocation();

        //设置地图zoom级别
        mMapController.setZoom(15);

        //设置Logo显示位置.
        map_view.setLogoPos(LOGO_RIGHT_BOTTOM);

        //矢量
        map_view.setMapType(MAP_TYPE_VEC);
        map_type_tv.setText("影像");
    }

    private void initPanel() {
        eventTypeList = new ArrayList<>();
        tipsList = new ArrayList<>();

        tips_view.setIsSingleCheck(true);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tipsList.clear();
                setTips(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void setTips(int parentPosition) {
        if (eventTypeList.isEmpty()) {
            return;
        }
        tips_view.removeAllViews();
        EventTypeBean.EventTypeData parent = eventTypeList.get(parentPosition);
        if (parent.Child != null) {
            for (EventTypeBean.EventTypeData child : parent.Child) {
                TipsItem item = new TipsItem();
                item.tipId = child.ID;
                item.tipName = child.Name;
                tipsList.add(item);
            }
            tips_view.initViews(tipsList, null);
        }
    }

    //定位
    @OnClick(R.id.positioning)
    public void positioning() {
        //定位到当前位置
        locateCurrentLocation();
    }

    //减
    @OnClick(R.id.subtract)
    public void subtract() {
        // 缩小一级
        mMapController.zoomOut();
    }

    //加
    @OnClick(R.id.add)
    public void add() {
        // 放大一级
        mMapController.zoomIn();
    }

    @OnClick(R.id.back)
    public void back() {
        onBackPressed();
    }

    //地图模式切换
    @OnClick(R.id.map_type_ll)
    public void mapTypeLl() {
        //当前是影像
        if (map_view.getMapType() == MAP_TYPE_IMG) {
            map_type_iv.setImageResource(R.mipmap.icon_satellite);
            map_view.setMapType(MAP_TYPE_VEC);
            map_type_tv.setText("影像");
        } else if (map_view.getMapType() == MAP_TYPE_VEC) {
            map_type_iv.setImageResource(R.mipmap.icon_plane);
            //矢量
            map_view.setMapType(MAP_TYPE_IMG);
            map_type_tv.setText("平面");
        }
    }


    //语音
    @OnClick(R.id.btn_record)
    public void btnRecord() {
        //录音
        recordVoice();
    }

    //拍照
    @OnClick(R.id.btn_camera)
    public void btnCamera() {
        //拍照
        camera();
    }

    @OnClick(R.id.btn_report_event)
    public void reportEvent() {
        String eventTypeId = "";
        String description = "";

        boolean isSelectType = false;
        for (TipsItem item : tipsList) {
            if (item.isChecked) {
                isSelectType = true;
                eventTypeId = item.tipId;
            }
        }
        if (!isSelectType) {
            ToastUtils.show("请选择事件类型");
            return;
        }

        description = et_remark.getText().toString().trim();
        if (TextUtils.isEmpty(ImagePath) && TextUtils.isEmpty(VideoPath)) {
            ToastUtils.show("至少添加一个图片或视频");
            return;
        }
        String longitude = "";
        String latitude = "";
        GeoPoint point = getCurrentLocation();
        if (point == null) {
            ToastUtils.show("无法获取当前位置，请检查是否开启GPS位置信息");
            return;
        }
        longitude = String.valueOf((double) point.getLongitudeE6() / 1E6);
        latitude = String.valueOf((double) point.getLatitudeE6() / 1E6);

        loadingDialog.show();

        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        params.put("IsCheckRepeat", "1");
        params.put("UID", CustomUtils.getUUID());
        params.put("longitude", longitude);
        params.put("latitude", latitude);
        params.put("ReportingType", "2");
        params.put("EventTypeID", eventTypeId);
        params.put("Description", description);
        params.put("ImagePath", ImagePath);
        params.put("VoicePath", VoicePath);
        params.put("VideoPath", VideoPath);
        params.put("ThumbnailPath", ThumbnailPath);

        Call<ReportEventBean> call = HttpService.getInstance().reportEvent(params);
        call.enqueue(new Callback<ReportEventBean>() {
            @Override
            public void onResponse(@NonNull Call<ReportEventBean> call, @NonNull Response<ReportEventBean> response) {
                loadingDialog.dismiss();
                //数据请求成功
                LogUtils.v("gogogo report event result = " + JsonUtils.toJson(response.body()));
                if (response.body() == null) {
                    //数据请求失败
                    ToastUtils.show("请求结果为空");
                    return;
                }
                if (TextUtils.equals(response.body().getCode(), "200")) {
                    ReportEventBean.ReportEventData Data = response.body().getData();
                    if (Data != null && Data.EventID > 0) {
                        ToastUtils.show("上报成功");
                        EventBus.getDefault().post(new WebRefreshEvent(""));
                        finish();
                    } else {
                        ToastUtils.show(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                    }
                } else {
                    ToastUtils.show(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                }
            }

            @Override
            public void onFailure(@NonNull Call<ReportEventBean> call, @NonNull Throwable t) {
                //数据请求失败
                loadingDialog.dismiss();
                t.printStackTrace();
                LogUtils.v("gogogo on failure = " + t.getMessage());
                ToastUtils.show("请求失败，请重试");
            }
        });
    }

    //定位到当前位置
    private void locateCurrentLocation() {
        //获得当前位置
        GeoPoint myLocation = myLocationOverlay.getMyLocation();

        //设置地图中心点
        mMapController.setCenter(myLocation);

        //动画移动到当前位置
        mMapController.animateTo(myLocation);

        //逆向地理编码获取地址
        searchGeoDecode(myLocation);
    }

    private GeoPoint getCurrentLocation() {
        return myLocationOverlay.getMyLocation();
    }

    //录音
    private void recordVoice() {
        AudioRecordDialog dialog = new AudioRecordDialog(this);
        dialog.setMaxSeconds(60);
        dialog.setOnAudioRecordCompleteListener(new AudioRecordDialog.OnAudioRecordCompleteListener() {
            @Override
            public void recordComplete(String filePath, int during) {
                HashMap<String, String> params = new HashMap<>();
                params.put("Token", CustomUtils.getToken());
                params.put("IsCheckRepeat", "1");
                params.put("UID", CustomUtils.getUUID());
                AttachmentEntity attachmentEntity = new AttachmentEntity(1, AttachmentHelper.getFileName(filePath), new File(filePath), during);
                if (loadingDialog != null) {
                    loadingDialog.show();
                }
                ((AlarmPresenter) presenter).uploadFile(params, attachmentEntity);
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    //拍照
    private void camera() {
        CameraSelectionDialog dialog = new CameraSelectionDialog(this);
        dialog.show();
    }

    //播放录音
    private void playVoice(String filePath) {
        PlayAudioRecordDialog dialog = new PlayAudioRecordDialog(this);
        dialog.showDialog(filePath, new PlayAudioRecordDialog.OnPlayVoiceErrorListener() {
            @Override
            public void onError() {
                ToastUtils.show("录音播放异常，请重试");
            }
        });
    }

    private void tryToPlayVideo(String path) {
        String fileName = StringUtil.getUrlParam(path, "filename");
        File file = new File(AttachmentHelper.getFilePath(fileName));
        if (file.exists()) {
            playVideo(file.getAbsolutePath());
        } else {
            if (loadingDialog != null) {
                loadingDialog.show();
            }
            download(path, fileName);
        }
    }

    // 播放视频
    private void playVideo(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        Context context = this;
        Dialog dialog = new Dialog(context, R.style.PlayVideoDialog);
        dialog.setCanceledOnTouchOutside(false);
        //创建video view
        RelativeLayout relativeLayout = new RelativeLayout(context);
        VideoView mVideoView = new VideoView(context);
        mVideoView.setVideoPath(path);
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                LogUtils.v("gogogo play video complete");
                dialog.dismiss();
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                LogUtils.v("gogogo play video fail");
                dialog.dismiss();
                boolean isDelete = AttachmentHelper.deleteFile(path);
                LogUtils.v("gogogo delete file = " + isDelete);
                ToastUtils.show("视频播放异常，请重试");
                return false;
            }
        });
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        relativeLayout.addView(mVideoView, layoutParams);
        //dialog添加view
        ViewGroup.LayoutParams rootLayoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        dialog.setContentView(relativeLayout, rootLayoutParams);
        Window mWindow = dialog.getWindow();
        if (mWindow != null) {
            WindowManager.LayoutParams lp = mWindow.getAttributes();
            int mScreenWidth = DisplayUtil.getScreenWidth(context);
            int mScreenHeight = DisplayUtil.getScreenHeight(context);
            lp.width = mScreenWidth; // 宽度
            lp.height = (int) (mScreenHeight * 0.6); // 高度
            mWindow.setAttributes(lp);
        }
        dialog.show();
        mVideoView.start();
    }

    private void searchGeoDecode(GeoPoint geoPoint) {
        // 开始搜索
        if (mGeoDecode == null) {
            mGeoDecode = new TGeoDecode(this);
        }
        if (geoPoint != null) {
            mGeoDecode.search(geoPoint);
        }
    }

    @Override
    public void onGeoDecodeResult(TGeoAddress addr, int errCode) {
        if (errCode != TErrorCode.OK) {
            return;
        }
        if (addr == null) {
            return;
        }

    }

    private ImageView createImageAttachmentItem() {
        ImageView imageView = new ImageView(this);
        // 图片附件宽度90，其他附件宽度60
        int dp90 = DensityUtil.dp2px(90);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp90, ViewGroup.LayoutParams.MATCH_PARENT);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        imageView.setLayoutParams(layoutParams);
        return imageView;
    }

    private View createVoiceAttachmentItem(int during) {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_add_media_attachment, null);
        TextView tv_title = view.findViewById(R.id.tv_title);
        TextView tv_desc = view.findViewById(R.id.tv_desc);
        voiceCount++;
        tv_title.setText("录音" + voiceCount);
        tv_desc.setText(during + "''");
        int dp90 = DensityUtil.dp2px(90);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp90, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        view.setLayoutParams(layoutParams);
        return view;
    }

    private View createVideoAttachmentItem(String thumb) {
        View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_add_video_attachment, null);
        ImageView iv_thumb = view.findViewById(R.id.iv_thumb);
        ExploreImageLoader.getInstance().loadImage(getApplicationContext(), thumb, iv_thumb);
        int dp90 = DensityUtil.dp2px(90);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(dp90, ViewGroup.LayoutParams.MATCH_PARENT);
        layoutParams.rightMargin = DensityUtil.dp2px(10);
        view.setLayoutParams(layoutParams);
        return view;
    }

    private void requestData() {
        HashMap<String, String> params = new HashMap<>();
        params.put("Token", CustomUtils.getToken());
        if (isFireAlarm) {
            //火情报警添加参数筛选类型
            params.put("type", "1");
        }
        Call<EventTypeBean> call = HttpService.getInstance().getEventType(params);
        call.enqueue(new Callback<EventTypeBean>() {
            @Override
            public void onResponse(@NonNull Call<EventTypeBean> call, @NonNull Response<EventTypeBean> response) {
                loadingDialog.dismiss();
                //数据请求成功
                LogUtils.v("gogogo get event type result = " + JsonUtils.toJson(response.body()));
                if (response.body() == null) {
                    //数据请求失败
                    ToastUtils.show("请求结果为空");
                    return;
                }
                if (TextUtils.equals(response.body().getCode(), "200")) {
                    List<EventTypeBean.EventTypeData> typeList = response.body().getData();
                    //防止空指针
                    if (typeList == null) {
                        typeList = new ArrayList<>();
                    }
                    eventTypeList.clear();
                    eventTypeList.addAll(typeList);

                    for (int i = 0; i < eventTypeList.size(); i++) {
                        EventTypeBean.EventTypeData parent = eventTypeList.get(i);
                        tabLayout.addTab(tabLayout.newTab().setText(parent.Name), i == 0);
                    }
                    //初始显示第0个父分类的子分类
                    tipsList.clear();
                    setTips(0);
                } else {
                    ToastUtils.show(TextUtils.isEmpty(response.body().getErrorMsg()) ? "请求失败，请重试" : response.body().getErrorMsg());
                }
            }

            @Override
            public void onFailure(@NonNull Call<EventTypeBean> call, @NonNull Throwable t) {
                loadingDialog.dismiss();
                //数据请求失败
                t.printStackTrace();
                ToastUtils.show("请求失败，请重试");
            }
        });
    }

    @Override
    public void uploadFileSuccess(UploadFileBean.UploadFileData Data, int attachmentType, int during) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        String fileName = Data.FileName;
        String ThumbnailFile = Data.ThumbnailFile;

        if (attachmentType == 1) {
            View itemView = createVoiceAttachmentItem(during);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVoice(fileName);
                }
            });
            ll_attachment.addView(itemView);
            //添加到提交参数中
            if (TextUtils.isEmpty(VoicePath)) {
                VoicePath = StringUtil.getUrlParam(fileName, "filename");
            } else {
                VoicePath += "|";
                VoicePath += StringUtil.getUrlParam(fileName, "filename");
            }
        } else if (attachmentType == 2) {
            ImageView itemView = createImageAttachmentItem();
            ExploreImageLoader.getInstance().loadImage(getApplicationContext(), fileName, itemView);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString("imgUrl", fileName);
                    Intent intent = new Intent(FireAlarmActivity.this, BrowseImageActivity.class);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            });
            ll_attachment.addView(itemView);
            //添加到提交参数中
            if (TextUtils.isEmpty(ImagePath)) {
                ImagePath = StringUtil.getUrlParam(fileName, "filename");
            } else {
                ImagePath += "|";
                ImagePath += StringUtil.getUrlParam(fileName, "filename");
            }
        } else if (attachmentType == 3) {
            View itemView = createVideoAttachmentItem(ThumbnailFile);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tryToPlayVideo(fileName);
                }
            });
            ll_attachment.addView(itemView);
            //添加到提交参数中
            if (TextUtils.isEmpty(VideoPath)) {
                VideoPath = StringUtil.getUrlParam(fileName, "filename");
            } else {
                VideoPath += "|";
                VideoPath += StringUtil.getUrlParam(fileName, "filename");
            }
            if (TextUtils.isEmpty(ThumbnailPath)) {
                ThumbnailPath = StringUtil.getUrlParam(ThumbnailFile, "filename");
            } else {
                ThumbnailPath += "|";
                ThumbnailPath += StringUtil.getUrlParam(ThumbnailFile, "filename");
            }
        }
    }

    @Override
    public void alarmSuccess() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show("上报成功");
        finish();
    }

    @Override
    public void fail(String msg) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        ToastUtils.show(msg);
    }

    //视频附件下载
    private Thread downloadThread;

    private void download(String fileUrl, String fileName) {
        Call<ResponseBody> call = HttpService.getInstance().downloadFile(fileUrl);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                if (response.body() != null) {
                    LogUtils.v("gogogo download file result = " + response.message() + "  length  " + response.body().contentLength() + "  type " + response.body().contentType());
                    if (response.body().contentLength() <= 0) {
                        ToastUtils.show("附件下载失败，请检查附件地址是否正确");
                        return;
                    }
                    ToastUtils.show("正在下载附件");
                    //建立一个文件
                    File file = AttachmentHelper.createFile(fileName);
                    //下载文件放在子线程
                    downloadThread = new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            //保存到本地
                            AttachmentHelper.writeFile2Disk(response, file, new ForestCampTaskVerifyEventContract.FileDownloadCallBack() {
                                @Override
                                public void onLoading(final long current, final long total) {
                                    if (current >= total) {
                                        if (file != null) {
                                            ToastUtils.show("下载完成");
                                            if (loadingDialog != null) {
                                                loadingDialog.dismiss();
                                            }
                                            Message msg = new Message();
                                            msg.what = 333;
                                            msg.obj = file.getAbsolutePath();
                                            handler.sendMessageDelayed(msg, 300);
                                        }
                                    }
                                }
                            });

                        }
                    };
                    downloadThread.start();

                } else {
                    ToastUtils.show("请求失败，请重试");
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                //数据请求失败
                t.printStackTrace();
                ToastUtils.show("请求失败，请重试");
            }
        });
    }

    //中断下载线程
    private void stopDownloadFile() {
        if (downloadThread != null && !downloadThread.isInterrupted()) {
            downloadThread.interrupt();
        }
        downloadThread = null;
    }

    @Override
    public void onDestroy() {
        stopDownloadFile();
        super.onDestroy();
    }

}
